<template>
    <div style="padding: 10px">
        <!-- 顶部 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="客户姓名">
                <el-input
                    v-model="formInline.name"
                    placeholder="请输入客户姓名"
                    style="width: 160px"
                    clearable
                />
            </el-form-item>
            <el-form-item label="客户手机">
                <el-input
                    v-model="formInline.phone"
                    placeholder="请输入客户手机号码"
                    style="width: 160px"
                    clearable
                />
            </el-form-item>
            <el-form-item label="归属人">
                <el-input
                    v-model="formInline.owner"
                    placeholder="请输入线索归属人"
                    style="width: 160px"
                    clearable
                />
            </el-form-item>
            <el-form-item label="渠道来源">
                <el-select
                    v-model="formInline.channelId"
                    placeholder="渠道来源"
                    style="width: 160px"
                    clearable
                >
                    <el-option
                        v-for="channel in channelData"
                        :key="channel.channelId"
                        :label="channel.channelName"
                        :value="channel.channelId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态">
                <el-select v-model="formInline.status" placeholder="渠道来源" style="width: 160px" clearable>
                    <el-option label="已分配" value="1" />
                    <el-option label="跟进中" value="2" />
                    <el-option label="回收" value="3" />
                    <el-option label="伪线索" value="4" />
                    <el-option label="未知" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item style="font-weight: 700" label="跟进时间">
                <el-date-picker
                    v-model="formInline.params"
                    type="datetimerange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="Search">搜索</el-button>
                <el-button type="primary" icon="Refresh" @click="Reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮 -->
        <div class="button">
            <el-button type="primary" size="small" icon="Plus" @click="newAddlist" plain>新增</el-button>
            <el-button
                type="success"
                size="small"
                icon="Edit"
                @click="editIdClue"
                :disabled="!isSingleRowSelected"
                plain
                >修改</el-button
            >
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                :disabled="!isDelect"
                @click="deleteClue"
                plain
                >删除</el-button
            >
            <el-button type="warning" size="small" icon="Download" plain>导出</el-button>
        </div>
        <!-- 表格 -->
        <el-table
            ref="multipleTableRef"
            :data="tableData"
            row-key="id"
            style="width: 100%; margin-top: 10px"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column property="clueId" label="线索编号" width="120">
                <!-- <template #default="scope">{{ scope.row.date }}</template> -->
            </el-table-column>
            <el-table-column property="name" label="客户姓名" width="120" />
            <el-table-column property="phone" label="手机号码" />
            <el-table-column property="channelName" label="渠道来源" />
            <el-table-column property="createTime" label="创建时间" />
            <el-table-column property="owner" label="线索归属" />
            <el-table-column label="线索状态">
                <template #default="scope">
                    <el-button size="small" type="primary" v-if="scope.row.status === 1" plain
                        >已分配</el-button
                    >
                    <el-button size="small" type="success" v-if="scope.row.status === 2" plain
                        >跟进中</el-button
                    >
                </template>
            </el-table-column>
            <el-table-column property="nextTime" label="下次跟进时间" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="text" icon="Pointer" @click="Allocation">分配</el-button>
                    <el-button type="text" icon="TopLeft" @click="() => jump(scope.row.clueId)"
                        >跟进</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
            v-model:current-page="pageParams.pageNum"
            v-model:page-size="pageParams.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :size="size"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="margin-top: 20px"
        />
        <!-- 新增修改 -->
        <el-dialog v-model="dialogVisible" :title="title" width="700" :before-close="handleClose">
            <el-form
                ref="ruleFormRef"
                style="max-width: 800px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                :inline="true"
            >
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="ruleForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入客户姓名" />
                </el-form-item>
                <el-form-item label="渠道来源">
                    <el-select v-model="ruleForm.channelId" placeholder="渠道来源" style="width: 200px">
                        <el-option
                            v-for="channel in channelData"
                            :key="channel.channelId"
                            :label="channel.channelName"
                            :value="channel.channelId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动信息">
                    <el-select v-model="ruleForm.activityId" placeholder="活动信息" style="width: 200px">
                        <el-option
                            v-for="channel in activityData"
                            :key="channel.activityId"
                            :label="channel.name"
                            :value="channel.activityId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="客户性别">
                    <el-radio-group v-model="ruleForm.gender" style="font-weight: normal">
                        <el-radio :value="0" style="margin-left: 20px; font-weight: normal">男</el-radio>
                        <el-radio :value="1" style="margin-left: 20px; font-weight: normal">女</el-radio>
                        <el-radio :value="2" style="margin-left: 20px; font-weight: normal">未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="客户年龄" style="margin-left: 45px">
                    <el-input-number
                        v-model="ruleForm.age"
                        :min="18"
                        :max="100"
                        @change="handleChange"
                        placeholder="年龄"
                    />
                </el-form-item>
                <el-form-item label="微信号">
                    <el-input v-model="ruleForm.weixin" placeholder="请输入微信号码" />
                </el-form-item>
                <el-form-item label="QQ号码">
                    <el-input v-model="ruleForm.qq" placeholder="请输入QQ号码" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 新增分配 -->
        <el-dialog v-model="dialogVisible1" title="分配线索" width="700" :before-close="handleClose1">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="归属部门">
                    <el-tree-select
                        v-model="value"
                        :data="treeData"
                        :value-key="'id'"
                        @change="handleTreeChange"
                        :render-after-expand="false"
                        style="width: 230px"
                    />
                </el-form-item>
                <el-form-item label="分配给">
                    <el-select
                        v-model="assignedUserId"
                        :options="assignedUsers"
                        placeholder="请选择用户"
                        style="width: 230px"
                        clearable
                    >
                        <el-option
                            v-for="user in assignedUsers"
                            :key="user.depId"
                            :label="user.nickName"
                            :value="user.depId"
                        />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="treeSelectsure">确定</el-button>
                    <el-button type="primary" @click="treeSelectcancel"> 取消 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ElRadioGroup, ElRadio, ElMessage } from 'element-plus';
import { toRaw } from '@vue/reactivity';
import { reactive, onMounted, ref, nextTick, computed } from 'vue';
import {
    allList,
    channels,
    activity,
    newAdd,
    editIdcon,
    editClue,
    deleteList,
    treeSelect,
    allocationget,
} from '../../../api/clue';
import type { ComponentSize } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Delete, Edit, Phone, Search } from '@element-plus/icons-vue';
const dialogVisible1 = ref(false);
const value = ref(null);
const treeData = ref([]);
const assignedUsers = ref([]); // 分配给的用户列表
const assignedUserId = ref(''); // 选中的用户ID

const isSingleRowSelected = computed(() => {
    return multipleSelection.value.length === 1;
});
const isDelect = computed(() => {
    return dataId.value.length !== 0;
});
interface RuleForm {
    name: string;
    activityId: number;
    age: number;
    channelId: number;
    gender: number;
    phone: string;
    qq: string;
    weixin: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    name: '',
    activityId: 0,
    age: 0,
    channelId: 0,
    gender: 0,
    phone: '',
    qq: '',
    weixin: '',
});
import { watch } from 'vue';
watch(
    () => ruleForm.channelId,
    newChannelId => {
        if (newChannelId) {
            ruleForm.activityId = 0;
            activityData.value = [{ activityId: 0 }];
            getActivity(newChannelId);
        } else {
            activityData.value = [{ activityId: 0 }];
            ruleForm.activityId = 0;
        }
    }
);
const handleRadioChange = () => {
    nextTick(() => {});
};
const tableData = ref<User[]>([]);
let total = ref(0);
const size = ref<ComponentSize>('default');
const disabled = ref(false);

// 客户年龄
const num = ref(1);
const handleChange = (value: number | undefined) => {
    console.log(value);
};
// 客户年龄
const formInline = reactive({
    name: '',
    phone: '',
    owner: '',
    channelId: '',
    status: '',
    params: '',
});
// 分页器方法
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    pageParams.pageSize = val;
    pageParams.pageNum = 1;
    getList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    pageParams.pageNum = val;
    getList();
};
// 表格---------------
import type { TableInstance } from 'element-plus';
interface User {
    channelName: string;
    clueId: number;
    createBy: string;
    createTime: string;
    name: string;
    nextTime: string;
    owner: string;
    phone: string;
    status: number;
}
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<User[]>([]);
const selectable = (row: User) => ![1, 2].includes(row.clueId);
const editId = ref<number | null>(null);
const dataId = ref<number[]>([]);
const handleSelectionChange = (val: User[]) => {
    const clonedVal = JSON.parse(JSON.stringify(val));
    multipleSelection.value = clonedVal;
    console.log(clonedVal);
    if (clonedVal.length === 1) {
        editId.value = clonedVal[0].clueId;
    } else {
        editId.value = null;
    }
    // 选中的删除id对象
    dataId.value = [];
    multipleSelection.value.filter(item => {
        dataId.value.push(item.clueId);
    });
    console.log(dataId.value);
};

// 获取表格数据
onMounted(() => {
    getList();
    getChannel();
    if (ruleForm.channelId) {
        getActivity();
    }
});
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
});
function getList() {
    allList(pageParams).then(res => {
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
    });
}
//获取渠道来源
interface Channel {
    channelId: number;
    channelName: string;
}
const channelData = ref<Channel[]>([]);
function getChannel() {
    channels().then(res => {
        channelData.value = res.data;
        console.log(res);
        console.log(channelData);
    });
}
// 获取活动信息
interface Activity {
    activityId: number;
    name: string;
}
const activityData = ref<Activity[]>([]);
function getActivity() {
    const channelId = ruleForm.channelId;
    console.log('当前选择的渠道ID:', channelId);

    activity(channelId).then(res => {
        console.log('活动信息响应:', res);
        activityData.value = res.data;
    });
}

// 查询-------
function Search() {
    allList(formInline).then(res => {
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
    });
}
// 重置---------
function Reset() {
    formInline.name = '';
    formInline.phone = '';
    formInline.owner = '';
    formInline.channelId = '';
    formInline.status = '';
    formInline.params = '';
    getList();
}
// 新增--------
import { ElMessageBox } from 'element-plus';
import { get } from 'http';
import { log } from 'console';

const dialogVisible = ref(false);

const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确认关闭弹窗吗')
        .then(() => {
            done();
        })
        .catch(() => {
            // catch error
        });
};

const locationOptions = ['Home', 'Company', 'School'];

const rules = reactive<FormRules<RuleForm>>({
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (title.value === '添加线索') {
            if (valid) {
                newAdd(ruleForm).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    });
                    ruleForm.name = '';
                    ruleForm.activityId = 0;
                    ruleForm.age = 18;
                    ruleForm.channelId = 0;
                    ruleForm.gender = 0;
                    ruleForm.phone = '';
                    ruleForm.qq = '';
                    ruleForm.weixin = '';
                    dialogVisible.value = false;
                });
                getList();
            } else {
                console.log('error submit!', fields);
            }
        } else {
            editClue(ruleForm)
                .then(res => {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    });
                    getList();
                    ruleForm.name = '';
                    ruleForm.activityId = 0;
                    ruleForm.age = 18;
                    ruleForm.channelId = 0;
                    ruleForm.gender = 0;
                    ruleForm.phone = '';
                    ruleForm.qq = '';
                    ruleForm.weixin = '';
                    dialogVisible.value = false;
                    dialogVisible.value = false;
                })
                .catch(err => {
                    console.error('修改失败', err);
                    ElMessage({
                        message: '修改失败，请重试',
                        type: 'error',
                    });
                });
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    ruleForm.name = '';
    ruleForm.activityId = 0;
    ruleForm.age = 18;
    ruleForm.channelId = 0;
    ruleForm.gender = 0;
    ruleForm.phone = '';
    ruleForm.qq = '';
    ruleForm.weixin = '';
    dialogVisible.value = false;
    dialogVisible.value = false;
};
let title = ref('');
function newAddlist() {
    title.value = '添加线索';
    dialogVisible.value = true;
}
//  修改---------
function editIdClue() {
    title.value = '编辑线索';
    dialogVisible.value = true;
    editIdcon(editId.value).then(res => {
        console.log(res);
        Object.assign(ruleForm, res.data);
    });
}

// 删除
function deleteClue() {
    const idsObj = dataId.value.join();
    console.log(idsObj);

    ElMessageBox.confirm(`确定要删除选中的编号为${idsObj}数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 调用删除API（根据API要求选择传递idsObj或idsArray）
        deleteList(idsObj)
            .then(res => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                getList();
            })
            .catch(error => {
                console.error('删除失败', error);
                ElMessage({
                    type: 'error',
                    message: '删除失败，请重试',
                });
            });
    });
}
// 分配
const handleClose1 = (done: () => void) => {
    ElMessageBox.confirm('Are you sure to close this dialog?')
        .then(() => {
            done();
        })
        .catch(() => {
            // catch error
        });
};
function Allocation() {
    dialogVisible1.value = true;
    treeSelect()
        .then(res => {
            console.log('获取部门数据成功');
            treeData.value = res.data;

            // 重置value，避免记忆之前的选择
            value.value = null;
        })
        .catch(err => {
            console.error('获取部门数据失败:', err);
            ElMessage.error('获取部门数据失败');
        });
}
// Allocation();
const handleTreeChange = selectedId => {
    console.log('选中的ID:', selectedId);
    value.value = selectedId;
    if (selectedId) {
        allocationget(selectedId)
            .then(res => {
                assignedUsers.value = res.data || [];
                assignedUserId.value = ''; // 重置用户选择
            })
            .catch(err => {
                console.error('获取用户失败:', err);
            });
    }
};
function treeSelectsure() {
    dialogVisible1.value = false;
    assignedUsers.value = [];
    assignedUserId.value = '';
}
function treeSelectcancel() {
    dialogVisible1.value = false;
    assignedUsers.value = [];
    assignedUserId.value = '';
}

import router from '@/router';

function jump(clueId) {
    console.log('当前行线索ID:', clueId);
    router.push({ path: `/clue/details/index/${clueId}/follow`, query: { clueId } });
}
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}
</style>
